home *** CD-ROM | disk | FTP | other *** search
/ Programming Microsoft Visual Basic .NET / Programming Microsoft Visual Basic .NET (Microsoft Press)(X08-78517)(2002).bin / 03 control flow and error handling / errorhandlingdemo / mainmodule1.vb < prev   
Encoding:
Text File  |  2002-03-16  |  13.6 KB  |  425 lines

  1.  
  2. Module MainModule
  3.  
  4.     Sub Main()
  5.         ' Run one of the Textxxxx procedures below by uncommenting only one statement
  6.  
  7.         'TestException()
  8.         'TestException2()
  9.         'TestMultipleExitPointFunction()
  10.         'TestCatchWhen()
  11.         'TestCatchWhen2()
  12.         'TestCatchWhen3()
  13.         'TestCustomException()
  14.         'TestGetExceptionMethod()
  15.         'TestInnerException()
  16.         'TestInnerException2()
  17.         'TestExceptionOverhead()
  18.         'TestOverflowExceptionOverhead()
  19.         'TestOnErrorPerformance()
  20.  
  21.         ' These statements are usuful when running inside Visual Studio.NET
  22.         Console.WriteLine("")
  23.         Console.WriteLine(">>> press Enter to terminate the program <<<")
  24.         Console.ReadLine()
  25.     End Sub
  26.  
  27.     ' this procedure test Exception properties
  28.  
  29.     Sub TestException()
  30.         ' display the ToString property of an exception object
  31.         ' NOTE: you get different results, depending on whether you compile this code
  32.         '       with or without debug information
  33.         Try
  34.             Throw New DivideByZeroException()
  35.         Catch ex As Exception
  36.             Console.WriteLine(ex.ToString)
  37.             ' Uncomment next line to see the stack trace 
  38.             ' Console.WriteLine(ex.StackTrace)
  39.         End Try
  40.     End Sub
  41.  
  42.     ' this procedure tests the Finally block
  43.  
  44.     Sub TestException2()
  45.         Dim cdir As String
  46.         Try
  47.             ' Remember the current directory.
  48.             cdir = FileSystem.CurDir()
  49.             ' Change to another directory
  50.             FileSystem.ChDir("c:\docs")
  51.             ' ....
  52.         Catch ex As Exception
  53.             ' Deal here with errors.
  54.             ' ...
  55.         Finally
  56.             ' In all cases, restore the current directory.
  57.             FileSystem.ChDir(cdir)
  58.         End Try
  59.     End Sub
  60.  
  61.     ' this procedure demonstrates using Try blocks for functions with multiple exit points
  62.  
  63.     Function TestMultipleExitPointFunction() As Integer
  64.         Dim x, y, z As Integer
  65.         Try
  66.             ' ...
  67.             If x > 0 Then Return 1
  68.             ' ...
  69.             If y = 0 Then Return 2
  70.             ' ...
  71.             If z > 0 Then Return 3
  72.             ' ...
  73.             Return 4
  74.         Finally
  75.             ' This code runs whatever exit path the code takes.
  76.             ' ...
  77.             Console.Write("This function is returning the value ")
  78.             Console.WriteLine(TestMultipleExitPointFunction)
  79.         End Try
  80.     End Function
  81.  
  82.     Sub TestCatchWhen()
  83.         Dim x, y, z, res As Integer    ' All variables are zero
  84.  
  85.         Try
  86.             ' You can see different behaviors by commenting out or changing
  87.             ' the order of the following statements
  88.  
  89.             ' ...
  90.             res = y \ x
  91.             ' ...
  92.             res = x \ y
  93.             ' ...
  94.             res = x \ z
  95.         Catch ex As DivideByZeroException When (x = 0)
  96.             Console.WriteLine("Division error: x is null.")
  97.         Catch ex As DivideByZeroException When (y = 0)
  98.             Console.WriteLine("Division error: y is null.")
  99.         Catch ex As DivideByZeroException
  100.             Console.WriteLine("Division error: no information on variables")
  101.         Catch
  102.             Console.WriteLine("An error has occurred.")
  103.         End Try
  104.     End Sub
  105.  
  106.     ' this procedure shows the When clause used with properties of the exception object
  107.  
  108.     Sub TestCatchWhen2()
  109.         Try
  110.             ' comment out next statement to see the behavior when another file is missing
  111.             FileOpen(1, "c:\myapp.ini", OpenMode.Input)
  112.             FileOpen(2, "c:\xxxxx.dat", OpenMode.Input)
  113.  
  114.         Catch ex As System.IO.FileNotFoundException When InStr(ex.Message, """c:\myapp.ini""") > 0
  115.             ' the ini file is missing.
  116.             Console.WriteLine("Can't initializa: MyApp.Ini file not found")
  117.         Catch ex As System.IO.FileNotFoundException
  118.             ' Another file wasn't found - extract the file name from the Message property.
  119.             Dim filename As String = Split(ex.Message, """")(1)
  120.             Console.WriteLine("The following file is missing: " & filename)
  121.             Debug.WriteLine(ex.message)
  122.         End Try
  123.     End Sub
  124.  
  125.     ' this procedure shows how to use the When clause to track where the error occurred
  126.  
  127.     Sub TestCatchWhen3()
  128.         Dim currentStep As Integer      ' You might also use an Enum value.
  129.  
  130.         Try
  131.             ' Initialize the program.
  132.             currentStep = 1
  133.  
  134.             ' comment and uncomment the Throw statements, so that you can simulate
  135.             ' an exception in different places of this procedure
  136.  
  137.             Throw New System.Exception()
  138.  
  139.             ' Open the data file.
  140.             currentStep = 2
  141.             ' ...
  142.             Throw New System.IO.FileNotFoundException()
  143.  
  144.             ' ...
  145.             Throw New System.Exception()
  146.  
  147.             ' Process the file contents.
  148.             currentStep = 3
  149.             ' ...
  150.             Throw New System.Exception()
  151.  
  152.             ' ...and so on ...
  153.  
  154.         Catch ex As Exception When currentStep = 1
  155.             Console.WriteLine("An error occurred in the initialization step.")
  156.  
  157.         Catch ex As System.IO.FileNotFoundException When currentStep = 2
  158.             Console.WriteLine("The data file wasn't found.")
  159.  
  160.         Catch ex As Exception When currentStep = 2
  161.             Console.WriteLine("An error occurred while opening the data file.")
  162.  
  163.         Catch ex As Exception When currentStep = 3
  164.             Console.WriteLine("An error occurred while processing data.")
  165.             ' Add here other Catch blocks
  166.             ' ...
  167.         End Try
  168.     End Sub
  169.  
  170.     ' this procedure tests custom exception objects
  171.  
  172.     Sub TestCustomException()
  173.         Try
  174.             LoadIniFile()
  175.         Catch ex As UnableToLoadIniFileException
  176.             ' Deal with the most specific error here.
  177.             ' Next statement displays custom message "Unable to load..."
  178.             Console.WriteLine(ex.Message)
  179.         Catch ex As Exception
  180.             ' Deal with other errors here.
  181.         End Try
  182.     End Sub
  183.  
  184.     ' The routine that opens the INI file.
  185.     Sub LoadIniFile()
  186.         Try
  187.             ' Try to open the INI file. (cause an error in this demo)
  188.             FileOpen(1, "c:\missingfile.ini", OpenMode.Input)
  189.  
  190.         Catch ex As Exception
  191.             ' Whatever caused the error, throw a more specific exception.
  192.             Throw New UnableToLoadIniFileException()
  193.         End Try
  194.     End Sub
  195.  
  196.     ' test the Err.GetException method
  197.  
  198.     Sub TestGetExceptionMethod()
  199.         Try
  200.             Call OldStyleErrorHandlerProc()
  201.         Catch ex As DivideByZeroException
  202.             Console.WriteLine("A DivideByZeroException has been caught.")
  203.         End Try
  204.     End Sub
  205.  
  206.     ' this procedure traps an error using an old-style On Error Goto
  207.     ' and return it to the caller as an exception
  208.  
  209.     Sub OldStyleErrorHandlerProc()
  210.         On Error GoTo ErrorHandler
  211.  
  212.         ' cause a division by zero error
  213.         Dim x, y As Integer
  214.         y = 1 \ x
  215.  
  216.         Exit Sub
  217.  
  218. ErrorHandler:
  219.         ' add here clean up code as necessary
  220.         ' ...
  221.         ' report it to the caller as an Exception object
  222.         Throw Err.GetException
  223.     End Sub
  224.  
  225.     ' this procedure tests inner exceptions
  226.  
  227.     Sub TestInnerException()
  228.         Dim x, y As Integer
  229.  
  230.         Try
  231.             MathIntensiveProc(x, y)
  232.         Catch ex As ArgumentException
  233.             Console.WriteLine("An argument exception has occurred.")
  234.             ' Print a more detailed message about the actual cause of the error.
  235.             Console.WriteLine(ex.InnerException.Message)
  236.         Catch ex As Exception
  237.             ' Deal with other errors.
  238.             Console.WriteLine(ex.Message)
  239.         End Try
  240.     End Sub
  241.  
  242.     Sub MathIntensiveProc(ByVal x As Integer, ByVal y As Integer)
  243.         Try
  244.             ' Process arguments here.
  245.             ' ...
  246.             ' (cause a division by zero error to test this code)
  247.             x = 1 \ y
  248.         Catch ex As Exception
  249.             ' Map any exception to the ArgumentException object, 
  250.             ' but remember the inner (actual) exception object.
  251.             Throw New ArgumentException("Wrong arguments", ex)
  252.             Console.WriteLine(ex.GetBaseException.Message())
  253.         End Try
  254.     End Sub
  255.  
  256.     Sub TestInnerException2()
  257.         Try
  258.             InitializeApplication()
  259.         Catch ex As InitializationFailedException
  260.             ' Deal with the most specific error here.
  261.             ' Next statement displays custom message "Unable to load..."
  262.             Console.WriteLine(ex.Message)
  263.             ' also display a message from the inner exception
  264.             Console.WriteLine("Inner exception: " & ex.InnerException.Message)
  265.         Catch ex As Exception
  266.             ' Deal with other errors here.
  267.         End Try
  268.     End Sub
  269.  
  270.     ' The routine that opens the INI file.
  271.     Sub InitializeApplication()
  272.         Try
  273.             ' Try to open the INI file. (cause an error in this demo)
  274.             FileOpen(1, "c:\missingfile.ini", OpenMode.Input)
  275.  
  276.         Catch ex As Exception
  277.             ' Whatever caused the error, throw a more specific exception.
  278.             Throw New InitializationFailedException(ex)
  279.         End Try
  280.     End Sub
  281.  
  282.     ' this procedure tests exception overheads
  283.  
  284.     Dim rand As New Random()    ' random number generator
  285.  
  286.     Sub TestExceptionOverhead()
  287.         ' This is the probability that the called method raises an error
  288.         Const Probability As Double = 0.001
  289.         ' This is the number of repetitions 
  290.         Const Repetitions As Integer = 1000000
  291.  
  292.         Dim i As Integer
  293.         Dim startTime As Date
  294.         Dim errorCount As Integer
  295.  
  296.         ' test the method that notifies an error condition by throwing an exception.
  297.         startTime = Now
  298.         errorCount = 0
  299.         For i = 1 To Repetitions
  300.             Try
  301.                 CanThrowException(Probability)
  302.             Catch
  303.                 errorCount += 1
  304.             End Try
  305.         Next
  306.         Console.WriteLine("Exceptions: {0} secs. ", Now.Subtract(startTime))
  307.  
  308.         ' test the method that notifies an error condition by returning False.
  309.         startTime = Now
  310.         errorCount = 0
  311.         For i = 1 To Repetitions
  312.             If CanReturnFalse(Probability) = False Then
  313.                 errorCount += 1
  314.             End If
  315.         Next
  316.         Console.WriteLine("Return value:  {0} secs.", Now.Subtract(startTime))
  317.     End Sub
  318.  
  319.     ' this method can throw an exception with a given probability.
  320.     Sub CanThrowException(ByVal probability As Double)
  321.         If rand.NextDouble <= probability Then
  322.             Throw New System.Exception()
  323.         End If
  324.     End Sub
  325.  
  326.     ' This method can signal error condition by returning False
  327.     Function CanReturnFalse(ByVal probability As Double) As Boolean
  328.         If rand.NextDouble < probability Then
  329.             ' this simulates an error.
  330.             Return False
  331.         Else
  332.             ' this means a successful operation
  333.             Return True
  334.         End If
  335.     End Function
  336.  
  337.     ' this procedure benchmarks a simple integer addition.
  338.     ' you should compile this code with and without the Remove integer overflow check option
  339.  
  340.     Sub TestOverflowExceptionOverhead()
  341.         Dim start As Date
  342.         Dim i As Integer
  343.         Dim intVar As Integer
  344.         Dim lngVar As Long
  345.  
  346.         start = Now
  347.         For i = 1 To 1000000000
  348.             intVar = intVar + 1
  349.         Next
  350.         Console.WriteLine("Incrementing an Integer variable: {0} secs.", Now.Subtract(start))
  351.  
  352.         start = Now
  353.         For i = 1 To 1000000000
  354.             lngVar = lngVar + 1
  355.         Next
  356.         Console.WriteLine("Incrementing a Long variable: {0} secs.", Now.Subtract(start))
  357.     End Sub
  358.  
  359.     ' this procedure tests the overhead of On Error vs. Try-Catch
  360.  
  361.     Sub TestOnErrorPerformance()
  362.         Dim start As Date
  363.         Dim i As Integer
  364.         Dim res As Integer
  365.  
  366.         start = Now
  367.         For i = 1 To 10000000
  368.             res = TestOnErrorGotoOverhead()
  369.         Next
  370.         Console.WriteLine("TestOnErrorGotoOverhead: {0} secs.", Now.Subtract(start))
  371.  
  372.         start = Now
  373.         For i = 1 To 10000000
  374.             res = TestOnErrorResumeNextOverhead()
  375.         Next
  376.         Console.WriteLine("TestOnErrorResumeNextOverhead: {0} secs.", Now.Subtract(start))
  377.  
  378.         start = Now
  379.         For i = 1 To 10000000
  380.             res = TestTryCatchOverhead()
  381.         Next
  382.         Console.WriteLine("TestTryCatchOverhead: {0} secs.", Now.Subtract(start))
  383.  
  384.         start = Now
  385.         For i = 1 To 10000000
  386.             res = TestNoErrorTrappingOverhead()
  387.         Next
  388.         Console.WriteLine("TestNoErrorTrappingOverhead: {0} secs.", Now.Subtract(start))
  389.     End Sub
  390.  
  391.     ' auxiliary functions
  392.  
  393.     Function TestOnErrorGotoOverhead() As Integer
  394.         On Error GoTo ErrorHandler
  395.         Dim x As Integer = 123
  396.         x = x * x
  397. ErrorHandler:
  398.         TestOnErrorGotoOverhead = x \ 10
  399.     End Function
  400.  
  401.     Function TestOnErrorResumeNextOverhead() As Integer
  402.         On Error Resume Next
  403.         Dim x As Integer = 123
  404.         x = x * x
  405.         TestOnErrorResumeNextOverhead = x \ 10
  406.     End Function
  407.  
  408.     Function TestTryCatchOverhead() As Integer
  409.         Dim x As Integer = 123
  410.         Try
  411.             x = x * x
  412.         Finally
  413.             TestTryCatchOverhead = x \ 10
  414.         End Try
  415.     End Function
  416.  
  417.     Function TestNoErrorTrappingOverhead() As Integer
  418.         Dim x As Integer = 123
  419.         x = x * x
  420.         TestNoErrorTrappingOverhead = x \ 10
  421.     End Function
  422. End Module
  423.  
  424.  
  425.